﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using ZGLXM.Domain;
using ZGLXM.Infra.Interface;

namespace ZGLXM.Infra.Repository
{
    public class UserRepository : BaseRepository<User>, IUserRepository
    {
        private readonly BaseDataContext baseDataContext1;
        private readonly ILogger<BaseRepository<User>> logger1;
        public UserRepository(BaseDataContext baseDataContext, ILogger<BaseRepository<User>> logger) : base(baseDataContext, logger)
        {
            this.baseDataContext1 = baseDataContext;
            this.logger1 = logger;
        }


        /// <summary>
        /// 事务新增用户角色
        /// </summary>
        /// <param name="user"></param>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public async Task<bool> UserRoleInsert(User user, int[] roleIds)
        {
            try
            {
                var result = false;
                var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                try
                {
                    //新增用户
                    var userid = await baseDataContext1.Users.AddAsync(user);
                    await baseDataContext1.SaveChangesAsync();
                    //新增用户角色关联
                    foreach(var item in roleIds)
                    {
                        await baseDataContext1.AddAsync(new UserRole
                        {
                            UserId = userid.Entity.UserId,
                            RoleId = item
                        });
                    }
                    await baseDataContext1.SaveChangesAsync();
                    //提交事务
                    scope.Complete();
                    result = true;
                    return result;
                }
                finally
                {
                    //回滚事务
                    scope.Dispose();
                }
            }
            catch (Exception ex)
            {
                logger1.LogError("添加用户角色异常" + ex.Message); ;
                throw;
            }
        }
    }
}
